//
//  NSObject+Json.m
//  runtime
//
//  Created by eport on 2020/12/13.
//

//https://www.jianshu.com/p/e0d46032b27f
// https://www.jianshu.com/p/ecdb5fa307f8

#import "NSObject+Json.h"
#import <objc/runtime.h>
#import <objc/message.h>

@implementation NSObject (Json)

+ (instancetype)xwx_initWithDictionaryForModel:(NSDictionary *)dic{
    
    id myObj = [[self alloc] init];
    unsigned int outCount;
    //获取类中的所有成员属性
    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);
    
    for (NSInteger i = 0; i < outCount; i ++) {
        
        //获取属性名字符串
        objc_property_t property = arrPropertys[i];
        //model中的属性名
        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
        id propertyValue = dic[propertyName];
        
        //处理服务器字段与本地model字段不匹配问题
        if ([propertyName isEqualToString:@"age3"]) {//处理本地与网络字符不匹配的问题
            propertyValue = dic[@"age"];
        }
    
        if (propertyValue != nil) {
            [myObj setValue:propertyValue forKey:propertyName];
            
            
            
        }
        
    }
    //注意在runtime获取属性的时候，并不是ARC Objective-C的对象所有需要释放
    free(arrPropertys);
    return myObj;
}

@end
